/// <reference path="../interfaces/IUser.ts" />
module Sustainalytics.Accounts {

    interface IUsersController extends ng.IScope {
        initPage: any;
        getUsers: any;
        resetUsersList: any;
        resetPassword: any;
        uncheckAllUsers: any;
        accountsList: AccountsDto[];
        usersList: UsersDto[];
        userStatus: any;
        usersForm: any;
        count: any;
        orderby: string;
        descending: boolean;
        setOrder: any;
        search: any;
        displayedItems: any;
        checkSortBy: (column: string, direction: boolean) => boolean;
        statusChange: any;
        allUsersChecked: boolean;
        allUsersCheckedChanged: any;
        selectedUsersCounter: any;
        updateSelectedUsersCounter: any;
        userChecked: boolean;
        hideFilterContainer: any;
        openFilterContainer: any;
        showDiv: boolean;
        lastSyncWithCRM: Date;
    }
    class UsersController {
        constructor(private $scope: IUsersController, $rootScope, notificationFactory: INotificationFactory, staticObjects: IStaticObjects, userFactory: UsersService, sharedProperties) {

            $scope.initPage = () => {
                sharedProperties.setObject(null);
                $scope.usersList = [];
                $scope.accountsList = [];
                $scope.getUsers();
            }

            $scope.getUsers = () => {
                var listOptions = new Common.HttpGetOptionsDto();

                // get pager
                var pager: Sustainalytics.Pager.PagerController = $scope['pager'];

                // If pager is not defined then abort execution.
                // Current controller is created before Pager controller.
                if (!pager) {
                    $rootScope.loading = false;
                    return;
                }

                listOptions.skip = pager.pagingOptions.pageSize * (pager.pagingOptions.pageIndex - 1);
                listOptions.take = pager.pagingOptions.pageSize;
                listOptions.orderBy = [$scope.orderby];
                listOptions.orderAscending = !$scope.descending;

                var accountsIds = [];
                for (var i = 0; i < $scope.accountsList.length; i++) {
                    var account = $scope.accountsList[i];
                    if (account.isSelected)
                        accountsIds.push(account.id);
                }
                if (accountsIds.length > 0)
                    sharedProperties.setObject(accountsIds);

                userFactory.usersGetList(listOptions, accountsIds, $scope.userStatus, $scope.usersForm.searchText)
                    .then(data => {
                        $scope.usersList = data;
                        $scope.count = $scope.usersList.length;
                    });

                userFactory.usersGetLastCrmSync().then(data=> {
                    $scope.lastSyncWithCRM = new Date(data);
                });

                userFactory.usersGetAccountsList(new Common.HttpGetOptionsDto(), $scope.userStatus, $scope.usersForm.searchText)
                    .then(success=> {
                        var selectedAccoutsIds = sharedProperties.getObject();

                        var filter = $scope.usersForm.searchText == null || $scope.usersForm.searchText == "undefined" || $scope.usersForm.searchText == "" ? "" : $scope.usersForm.searchText;

                        $scope.accountsList = [];

                        angular.forEach(success, (account: AccountsDto) => {
                            if (selectedAccoutsIds != null && selectedAccoutsIds.length > 0) {
                                for (var i = 0; i < selectedAccoutsIds.length; i++) {
                                    if (selectedAccoutsIds[i] == account.id) {
                                        account.isSelected = true;
                                    }
                                }
                            }

                            $scope.accountsList.push(account);
                        });
                    });


                userFactory.usersGetCount($scope.userStatus, accountsIds, $scope.usersForm.searchText)
                    .then(data=> {
                        pager.totalItemsCount = data;
                    });

            };

            // subscribe to pager events
            $scope.$on('pagerChanged', function (event, pager) {
                // get accounts
                $scope.getUsers();
            });

            $scope.uncheckAllUsers = () => {
                angular.forEach($scope.usersList, (user) => {
                    user.isSelected = false;
                }, null);
            };

            $scope.resetPassword = () => {
                var listOfIds = Enumerable.From($scope.usersList)
                    .Where(x => x.isSelected == true).Select(x => x.id).ToArray();
                if (confirm("The password will be reset for " + listOfIds.length + (listOfIds.length > 1 ? " users." : " user.")
                    + "\n" + "Are you sure that you want to continue?"
                    )) {
                    userFactory.usersResetPasswords(listOfIds)
                        .then(result=> {
                            notificationFactory.success("The password has been reset for " + listOfIds.length + (listOfIds.length > 1 ? " users." : " user."));
                            $scope.uncheckAllUsers()
                        });
                }
            }

            $scope.orderby = 'fullName';
            $scope.descending = false;
            $scope.userStatus = 'Active';
            $scope.usersForm = { searchText: '' };
            $scope.lastSyncWithCRM = null;

            $scope.setOrder = (orderby) => {
                if (orderby === $scope.orderby) {
                    $scope.descending = !$scope.descending;
                }
                $scope.orderby = orderby;

                $scope.getUsers();
            };
            $scope.checkSortBy = (value, direction) => {
                return $scope.orderby === value && $scope.descending == direction;
            };
            $scope.statusChange = () => {
                $scope.usersForm.searchText = "";
                $scope.getUsers();
            };

            $scope.initPage();

            $scope.usersList = [];

            $scope.allUsersCheckedChanged = function () {
                for (var i = 0; i < $scope.usersList.length; i++) {
                    $scope.usersList[i].isSelected = !$scope.allUsersChecked;
                }
            };

            $scope.selectedUsersCounter = function () {
                var count = 0;
                angular.forEach($scope.usersList, function (user) {
                    count += user.isSelected ? 1 : 0;
                });

                return count;
            };

            $scope.openFilterContainer = function () {
                $scope.showDiv = true;
            }

        $scope.hideFilterContainer = function () {
                if ($scope.showDiv == true) {

                    var flag = true;

                    for (var i = 0; i < $scope.accountsList.length; i++) {
                        if ($scope.accountsList[i].isSelected) {
                            //   at least one account is selected
                            flag = false;
                            break;
                        }
                    }

                    if (flag) {
                        sharedProperties.setObject(null);
                        $scope.getUsers(false);
                    }
                    else {
                        $scope.getUsers();
                    }
                }

                $scope.showDiv = false;
            }

        $scope.resetUsersList = function () {
            sharedProperties.setObject(null);
            for (var i = 0; i < $scope.accountsList.length; i++) {
                $scope.accountsList[i].isSelected = false
                $scope.search.name = "";
            }
            $scope.getUsers();
            }
        }
    }

    appRoot.controller('UsersController', ['$scope', '$rootScope', 'notificationFactory', 'staticObjects', 'UsersService', 'sharedProperties', ($scope, $rootScope, notificationFactory, staticObjects, userFactory, sharedProperties) =>
        new UsersController($scope, $rootScope, notificationFactory, staticObjects, userFactory, sharedProperties)
    ]);
}